/**
 * 
 */
package kr.pe.johnkim.dayve.rest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import kr.pe.johnkim.dayve.provider.DayveItem;
import kr.pe.johnkim.dayve.provider.DayveItemEvent;
import kr.pe.johnkim.dayve.util.ExternalJoinConstant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/**
 * 아이템 이벤트 RESTfull 관련 기능들을 구현하는 클래스 이다.
 * 
 * @author johnkim
 *
 */
public class DayveItemEventRest {

	public static final String TAG = DayveItemEventRest.class.getSimpleName();
	
	// 서버 주소.
	public static final String SERVER_URL = ExternalJoinConstant.MOBILE_SERVER_URL;

	// 컨트롤러 매핑.
	public static final String MYHISTORY_ITEM_EVENT_CONTROLLER = "/myHistoryItemEventController";

	// Item Event 를 등록 한다.
	public static final String MYHISTORY_ITEM_EVENT_REGISTER = "/registerItemEvent";

	// Item Event 목록을 가져 온다.
	public static final String MYHISTORY_ITEM_EVENT_LIST = "/selectItemEventList";

	// Item Event 를 수정 한다.
	public static final String MYHISTGORY_ITEM_EVENT_UPDATE = "/updateItemEvent";

	// Item Event 를 비활성화 한다.
	public static final String MYHISTORY_ITEM_EVENT_DEACTIVATE = "/updateDeactivateItemEvent";
	
	/**
	 * Item Event 를 등록 한다.
	 * 
	 * @param dayveItemEvent
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveItemEvent registerItemEvent(DayveItemEvent dayveItemEvent) throws JSONException, IOException {
		Log.i(TAG, "registerItemEvent");
		
		JSONObject jsonItemEvent = new JSONObject();
		
		jsonItemEvent.put("comment", dayveItemEvent.getComment());
		jsonItemEvent.put("amount", dayveItemEvent.getAmount());
		jsonItemEvent.put("openItemEventYn", dayveItemEvent.getOpenItemEventYn());
		jsonItemEvent.put("favoriteYn", dayveItemEvent.getFavoriteYn());
		jsonItemEvent.put("activateYn", dayveItemEvent.getActivateYn());
		jsonItemEvent.put("modifyDate", dayveItemEvent.getModifyDate());
		jsonItemEvent.put("registerDate", dayveItemEvent.getRegisterDate());
		jsonItemEvent.put("myHistoryMembersId", dayveItemEvent.getMyHistoryMembersId());
		jsonItemEvent.put("myHistoryItemsIdMyHistoryItems", dayveItemEvent.getMyHistoryItemsIdMyHistoryItems());
		
		String jsonString = "{\"myHistoryItemEvent\":" + jsonItemEvent.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveItemEvent mDayveItemEvent = new DayveItemEvent();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_ITEM_EVENT_CONTROLLER + MYHISTORY_ITEM_EVENT_REGISTER);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonGroup = new JSONObject(line);
	            	JSONObject mJsonGroup2 = mJsonGroup.getJSONObject("myHistoryItemEvent");
	            	
	            	// SUCCESS or FAIL
	            	mDayveItemEvent.setResult(mJsonGroup2.getString("result"));
	        	}
	        }
	        
	        Log.i(TAG, "Success to register item event.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to register item event.");
		}
		
		return mDayveItemEvent;
	}
	
	/**
	 * Item Event 목록을 가져 온다.
	 * 
	 * @param dayveItem
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public ArrayList<DayveItemEvent> selectItemEventList(DayveItemEvent dayveItemEvent) throws JSONException, IOException {
		Log.i(TAG, "selectItemEventList");
		
		JSONObject jsonItemEvent = new JSONObject();		
		
		jsonItemEvent.put("activateYn", dayveItemEvent.getActivateYn());
		jsonItemEvent.put("myHistoryMembersId", dayveItemEvent.getMyHistoryMembersId());
//		jsonItemEvent.put("myHistoryItemsIdMyHistoryItems", dayveItemEvent.getMyHistoryItemsIdMyHistoryItems());
//		jsonItem.put("itemEventStart", dayveItemEvent.getItemEventStart());
//		jsonItem.put("itemEventCount", dayveItemEvent.getItemEventCount());
		
		String jsonString = "{\"myHistoryItemEvent\":" + jsonItemEvent.toString() + "}";
		
		Log.i(TAG, "jsonItemEvent : " + jsonString);
		
		ArrayList<DayveItemEvent> itemEventList = new ArrayList<DayveItemEvent>();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_ITEM_EVENT_CONTROLLER + MYHISTORY_ITEM_EVENT_LIST);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "postUrl : " + postUrl);
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONArray jsonArray = new JSONArray(line);
	            	
	            	Log.i(TAG, "jsonArray.length() : " + jsonArray.length());
	            	
	            	for(int i=0 ; i<jsonArray.length() ; i++) {
	            		JSONObject mJsonItem = jsonArray.getJSONObject(i);
		            	JSONObject mJsonItem2 = mJsonItem.getJSONObject("myHistoryItemEvent");
		            	
		            	DayveItemEvent mDayveItemEvent = new DayveItemEvent();
		            	
		            	mDayveItemEvent.setIdMyHistoryItemEvents(mJsonItem2.getString("idMyHistoryItemEvents"));
		            	mDayveItemEvent.setComment(mJsonItem2.getString("comment"));
		            	mDayveItemEvent.setAmount(mJsonItem2.getString("amount"));
		            	mDayveItemEvent.setOpenItemEventYn(mJsonItem2.getString("openItemEventYn"));
		            	mDayveItemEvent.setFavoriteYn(mJsonItem2.getString("favoriteYn"));
		            	mDayveItemEvent.setActivateYn(mJsonItem2.getString("activateYn"));
		            	mDayveItemEvent.setModifyDate(mJsonItem2.getString("modifyDate"));
		            	mDayveItemEvent.setRegisterDate(mJsonItem2.getString("registerDate"));
		            	mDayveItemEvent.setMyHistoryMembersId(mJsonItem2.getString("myHistoryMembersId"));
		            	mDayveItemEvent.setMyHistoryItemsIdMyHistoryItems(mJsonItem2.getString("myHistoryItemsIdMyHistoryItems"));
		            	
//		            	Log.i(TAG, "idMyHistoryItemEvents          : " + mDayveItemEvent.getIdMyHistoryItemEvents());
//		            	Log.i(TAG, "comment                        : " + mDayveItemEvent.getComment());
//		            	Log.i(TAG, "amount                         : " + mDayveItemEvent.getAmount());
//		            	Log.i(TAG, "openItemEventYn                : " + mDayveItemEvent.getOpenItemEventYn());
//		            	Log.i(TAG, "favoriteYn                     : " + mDayveItemEvent.getFavoriteYn());
//		            	Log.i(TAG, "activateYn                     : " + mDayveItemEvent.getActivateYn());
//		            	Log.i(TAG, "modifyDate                     : " + mDayveItemEvent.getModifyDate());
//		            	Log.i(TAG, "registerDate                   : " + mDayveItemEvent.getRegisterDate());
//		            	Log.i(TAG, "myHistoryMembersId             : " + mDayveItemEvent.getMyHistoryMembersId());
//		            	Log.i(TAG, "myHistoryItemsIdMyHistoryItems : " + mDayveItemEvent.getMyHistoryItemsIdMyHistoryItems());
//		            	Log.i(TAG, "---------------------------------------------------");
		            	
		            	itemEventList.add(mDayveItemEvent);
	            	}
	        	}
	        }
	        
	        Log.i(TAG, "Success to select item event  list.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to select item event list.");
		}
		
		return itemEventList;
	}

	/**
	 * Item Event 내용을 수정 한다.
	 * 
	 * @param dayveItemEvent
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveItemEvent updateItemEvent(DayveItemEvent dayveItemEvent) throws JSONException, IOException {
		Log.i(TAG, "updateItemEvent");
		
		JSONObject jsonItem = new JSONObject();
		
		jsonItem.put("idMyHistoryItemEvents", dayveItemEvent.getIdMyHistoryItemEvents());
		jsonItem.put("comment", dayveItemEvent.getComment());
		jsonItem.put("amount", dayveItemEvent.getAmount());
		jsonItem.put("openItemEventYn", dayveItemEvent.getOpenItemEventYn());
		jsonItem.put("favoriteYn", dayveItemEvent.getFavoriteYn());
		jsonItem.put("activateYn", dayveItemEvent.getActivateYn());
		jsonItem.put("modifyDate", dayveItemEvent.getModifyDate());
		jsonItem.put("myHistoryMembersId", dayveItemEvent.getMyHistoryMembersId());
		jsonItem.put("myHistoryItemsIdMyHistoryItems", dayveItemEvent.getMyHistoryItemsIdMyHistoryItems());
		
		String jsonString = "{\"myHistoryItemEvent\":" + jsonItem.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveItemEvent mDayveItemEvent = new DayveItemEvent();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_ITEM_EVENT_CONTROLLER + MYHISTGORY_ITEM_EVENT_UPDATE);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonCategory = new JSONObject(line);
	            	JSONObject mJsonCategory2 = mJsonCategory.getJSONObject("myHistoryItemEvent");
	            	
	            	// SUCCESS or FAIL
	            	mDayveItemEvent.setResult(mJsonCategory2.getString("result"));
	        	}
	        }
	        
			Log.i(TAG, "Success to update item event.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to update item event.");
		}
		
		return mDayveItemEvent;
	}

	/**
	 * Item Event 를 비활성화 한다.
	 * 
	 * @param dayveItemEvent
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveItemEvent updateDeactivateItemEvent(DayveItemEvent dayveItemEvent) throws JSONException, IOException {
		Log.i(TAG, "updateDeactivateItemEvent");
		
		JSONObject jsonItem = new JSONObject();

		jsonItem.put("idMyHistoryItemEvents", dayveItemEvent.getIdMyHistoryItemEvents());
		jsonItem.put("activateYn", dayveItemEvent.getActivateYn());
		jsonItem.put("modifyDate", dayveItemEvent.getModifyDate());
		jsonItem.put("myHistoryMembersId", dayveItemEvent.getMyHistoryMembersId());
		
		String jsonString = "{\"myHistoryItemEvent\":" + jsonItem.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveItemEvent mDayveItemEvent = new DayveItemEvent();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_ITEM_EVENT_CONTROLLER + MYHISTORY_ITEM_EVENT_DEACTIVATE);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonCategory = new JSONObject(line);
	            	JSONObject mJsonCategory2 = mJsonCategory.getJSONObject("myHistoryItemEvent");
	            	
	            	// SUCCESS or FAIL
	            	mDayveItemEvent.setResult(mJsonCategory2.getString("result"));
	        	}
	        }
	        
			Log.i(TAG, "Success to deactivate item event.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to deactivate item event.");
		}
		
		return mDayveItemEvent;
	}
}
